package grpc

import (
	"log"
	"net"
	"strconv"

	"code/common/config"
	pb "code/common/protos"

	"google.golang.org/grpc"
)

type server struct {
	pb.UnimplementedCodeServiceServer
}

var grpcServer *grpc.Server

func Start() {
	lis, err := net.Listen("tcp", ":"+strconv.Itoa(config.Config.Port))
	if err != nil {
		return
	}
	grpcServer, err = startConfigurableGrpc(lis)
	if err != nil {
		log.Panicf("failed to listen: %v", err)
	}
}

func startConfigurableGrpc(lis net.Listener) (grpcServer *grpc.Server, err error) {
	grpcServer = grpc.NewServer()
	pb.RegisterCodeServiceServer(grpcServer, &server{})

	go func() {
		err := grpcServer.Serve(lis)
		if err != nil {
			log.Panicf("failed to serve: %v", err)
		}
	}()

	return
}

func Stop() {
	grpcServer.Stop()
}
